from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import Rule
import scrapy, time
from w3lib.html import remove_tags
from kyqb_collection_spider.spiders.common import CommonCrawlSpider
from kyqb_collection_spider.items import KyqbCollectionSpiderItem


class IsroSpider(CommonCrawlSpider):
    name = 'isro'
    allowed_domains = ['isro.gov.in']
    start_urls = ['https://www.isro.gov.in/press-releases/2020']

    rules = (
        Rule(LinkExtractor(allow=r'press-releases/\d+'), callback='parse_item'),
        Rule(LinkExtractor(allow=r'press-releases/\d+\?page=\d+'), callback='parse_item'),
    )

    custom_settings = {
        'ITEM_PIPELINES': {'kyqb_collection_spider.pipelines.NewImagesPipeline': 5,
                           'kyqb_collection_spider.pipelines.KyqbCollectionSpiderPipeline': 600},
    }

    def parse_item(self, response):
        a_list = response.xpath('//*[@id="block-system-main"]/div/div/div[@class="view-content"]/table//tr')
        for a in a_list:
            href = response.urljoin(a.xpath('./td/a/@href').extract_first())
            if '/hi/' in href:
                continue
            else:
                if not self.redis.sismember(self.name, href):
                    yield scrapy.Request(url=href, callback=self.article)
                # else:
                #     return None

    def article(self, response):
        try:
            item = KyqbCollectionSpiderItem()
            item['data_address'] = response.url
            item['website_name'] = 'ISRO'
            item['spider_name'] = self.name
            item['data_source_type'] = '新闻媒体'
            item['data_type'] = 'NEWS'
            item['collection_mode'] = 'spider'
            item['collection_time'] = time.strftime('%Y-%m-%d %H:%M:%S')
            timestamp = response.xpath('//*[@id="block-system-main"]/div/div/div/div/div/text()').extract_first().strip()
            item['publish_time'] = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(timestamp, "%b %d, %Y"))
            title = response.xpath('//*[@id="block-system-main"]/div/div/div/div/div/h2/text()').extract_first()
            item['title'] = remove_tags(title)
            item['abstract'] = None
            item['topic'] = None
            ps = response.xpath('//*[@id="block-system-main"]/div/div/div/div/div//p|'
                                '//*[@id="block-system-main"]/div/div/div/div/div//span|'
                                '//*[@id="block-system-main"]/div/div/div/div/div//li|'
                                '//*[@id="block-system-main"]/div/div/div/div/div/div')
            texts = []
            for p in ps:
                containers = p.xpath('./text()').extract()
                for container in containers:
                    text = remove_tags(container).strip()
                    texts.append(text)
            item['text'] = '\n'.join(texts)
            item['author'] = None
            image_urls = set()
            urls = response.xpath('//*[@id="block-system-main"]/div/div/div/div/div/p')
            for url in urls:
                url = response.urljoin(url.xpath('./img/@src').extract_first())
                if '.jpg' in url:
                   image_urls.add(url)
            item['image_urls'] = list(image_urls)
            yield item
            a_list = response.xpath('//*[@id="block-views-latest-news-block-1"]//table//tr')
            for a in a_list:
                href = response.urljoin(a.xpath('./td/a/@href').extract_first())
                if '/hi/' in href:
                    continue
                else:
                    if not self.redis.sismember(self.name, href):
                        yield scrapy.Request(url=href, callback=self.article)
        except Exception as e:
            self.logger.debug(f"采集错误:{response.url}\n{e}")
